import { createRequire } from 'module';
import { Permissions } from '../all/all.js';
import { exec } from 'child_process';
import util from 'util';
import net from 'net';

const require = createRequire(import.meta.url);
const execPromise = util.promisify(exec);
const serverPort = 2536; // 服务器监听的端口号
const _path = process.cwd() + '/plugins/xiaocheng_Minecraft/';
let timer;

export class admin extends plugin {
    constructor() {
        super({
            name: '管理|更新插件',
            dsc: '管理和更新代码',
            event: 'message',
            priority: 400,
            rule: [
                {
                    reg: '^(#|/)?橙子mc(插件)?(强制)?更新',
                    fnc: 'checkout',
                },
            ],
        });
    }

    async checkout(e) {
        let qq = e.user_id;
        let yanzheng = await Permissions(qq, 5, e);
        if (!yanzheng) return;

        const isForce = this.e.msg.includes('强制');
        let command = `git -C ${_path} pull --no-rebase`;
        if (isForce) {
            command = `git -C ${_path} reset --hard HEAD && ${command}`;
            await this.e.reply('正在执行强制更新操作，请稍等');
        } else {
            await this.e.reply('正在执行更新操作，请稍等');
        }

        try {
            const { stdout, stderr } = await execPromise(command, { cwd: _path });

            // 检查是否已经是最新版本
            if (/(Already up[ -]to[ -]date|已经是最新的)/.test(stdout)) {
                await this.e.reply('目前已经是最新版橙子mc插件了~');
                return;
            }

            // 更新成功的消息
            let say = `橙子mc插件更新成功！\n正在尝试重新启动Yunzai以应用更新...`;
            await this.e.reply(say) + e.reply('一般来说不可能自动重启成功，请手动重启。');

            // 清除之前的定时器（如果有的话）
            timer && clearTimeout(timer);
            timer = setTimeout(async () => {
                try {
                    // 等待之前的服务器进程完全关闭
                    await waitForServerShutdown();

                    // 重新启动服务器
                    let restartCommand = process.argv[1].includes('pm2') ? 'pnpm run restart' : 'pnpm run start';
                    await execPromise(restartCommand);

                    // 重启成功消息
                    console.log('重启成功，运行已转为后台');
                    console.log('查看日志请用命令：pnpm run log');
                    console.log('停止后台运行命令：pnpm stop');
                } catch (error) {
                    console.error('自动重启失败，请手动重启以应用新版spacexiao_minecraft。');
                    console.error('错误信息：', error);
                }
            }, 1000);
        } catch (error) {
            console.error('更新插件时出现错误：', error);
        }
    }
}

// 等待服务器进程完全关闭
async function waitForServerShutdown() {
    return new Promise((resolve, reject) => {
        const client = new net.Socket();
        client.on('error', () => {
            // 如果连接失败，说明服务器已经关闭
            client.destroy();
            resolve();
        });
        client.connect(serverPort, () => {
            // 如果连接成功，说明服务器还在运行，继续等待
            client.end();
            setTimeout(() => {
                waitForServerShutdown().then(resolve);
            }, 1000);
        });
    });
}
